#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <iostream>   
#include <list>   
#include <numeric>   
#include <algorithm>   
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>


//两个有用的宏定义：检查和赋值并且检测
#define CHK(eval) if(eval < 0){perror("eval"); exit(-1);}
#define CHK2(res, eval) if((res = eval) < 0){perror("eval"); exit(-1);}


#define BUF_SIZE  1024*1024
#define EPOLL_SIZE  1024

using namespace std;

char message[BUF_SIZE];     //接受服务器信息
list<int> list_of_clients;  //存放所有客户端
int res;
clock_t tStart;

int main(int argc, char *argv[])
{
    int sock;
    struct sockaddr_in addr;
    addr.sin_family = PF_INET;
    addr.sin_port = htons(8084);
    addr.sin_addr.s_addr = inet_addr("10.142.93.12");
    clock_t tStart;  //计算程序运行时间 
    tStart = clock();
    printf("start..\n");
    for(int i=0 ; i<EPOLL_SIZE; i++)  //生成EPOLL_SIZE个客户端，这里是10000个，模拟高并发
    {
       printf("i==%d\n", i);
       CHK2(sock,socket(PF_INET, SOCK_STREAM, 0));
       CHK(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0);
       list_of_clients.push_back(sock);

       bzero(&message, BUF_SIZE);
       CHK2(res,recv(sock, message, BUF_SIZE, 0));
       
       printf("%s\n", message);
       
    }
 
   
    list<int>::iterator it;          //移除所有客户端
    for(it = list_of_clients.begin(); it != list_of_clients.end() ; it++){
        bzero(message, BUF_SIZE);
        sprintf(message, "toooo seChat! fromID is: Client #%d", *it);
        send(*it, message, BUF_SIZE, 0);       
        close(*it);
    }
       
 
    printf("Test passed at: %.2f second(s)\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    printf("Total server connections was: %d\n", EPOLL_SIZE);

    return 0;
}